/**
 * 排行榜路由 - Expo Router
 * 显示用户排行榜、统计信息和成就
 * 使用 Expo Router 的文件路由系统
 * 
 * 作者：AI语言学习应用开发团队
 * 创建时间：2024年
 * 更新时间：2024年
 */
import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
  RefreshControl,
  Dimensions,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect, useRouter } from 'expo-router';
import AsyncStorage from '@react-native-async-storage/async-storage';

// 导入自定义组件
import { AppHeader } from '../components/Headers';
import { StatisticsGrid, AchievementsList, BottomTip } from '../components/ScreenComponents';

const { width: screenWidth } = Dimensions.get('window');

/**
 * 排行榜组件 - 显示排行榜和成就
 * 功能包括：用户排名、学习统计、成就展示等
 */
export default function LeaderboardScreen() {
  // 路由导航钩子
  const router = useRouter();
  
  // 状态管理
  const [userProgress, setUserProgress] = useState({
    currentStreak: 0,
    totalXP: 0,
    lessonsCompleted: 0,
    completedLessons: [],
    achievements: [],
    lastStudyDate: null,
  });
  
  const [refreshing, setRefreshing] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  // 模拟排行榜数据
  const [leaderboardData] = useState([
    { id: 1, name: '学习达人', xp: 2580, streak: 15, avatar: '🏆' },
    { id: 2, name: '英语高手', xp: 2340, streak: 12, avatar: '⭐' },
    { id: 3, name: '你', xp: 0, streak: 0, avatar: '😊' }, // 用户自己
    { id: 4, name: '单词王者', xp: 1950, streak: 8, avatar: '📚' },
    { id: 5, name: '语法专家', xp: 1720, streak: 10, avatar: '✨' },
    { id: 6, name: '口语达人', xp: 1650, streak: 6, avatar: '🎤' },
    { id: 7, name: '听力高手', xp: 1580, streak: 9, avatar: '👂' },
    { id: 8, name: '翻译专家', xp: 1420, streak: 7, avatar: '🔄' },
  ]);

  /**
   * 从本地存储加载用户进度数据
   */
  const loadUserProgress = async () => {
    try {
      const [xpData, streakData, completedData, achievementsData, lastDateData] = await Promise.all([
        AsyncStorage.getItem('totalXP'),
        AsyncStorage.getItem('currentStreak'),
        AsyncStorage.getItem('completedLessons'),
        AsyncStorage.getItem('achievements'),
        AsyncStorage.getItem('lastStudyDate'),
      ]);

      const totalXP = xpData ? parseInt(xpData) : 0;
      const currentStreak = streakData ? parseInt(streakData) : 0;
      const completedLessons = completedData ? JSON.parse(completedData) : [];
      const achievements = achievementsData ? JSON.parse(achievementsData) : [];
      const lastStudyDate = lastDateData || null;

      setUserProgress({
        totalXP,
        currentStreak,
        lessonsCompleted: completedLessons.length,
        completedLessons,
        achievements,
        lastStudyDate,
      });

      // 更新排行榜中用户的数据
      const updatedLeaderboard = leaderboardData.map(user => 
        user.name === '你' ? { ...user, xp: totalXP, streak: currentStreak } : user
      );
      
      // 重新排序排行榜
      updatedLeaderboard.sort((a, b) => b.xp - a.xp);
      
    } catch (error) {
      console.error('加载用户进度失败:', error);
      Alert.alert('错误', '加载数据失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 下拉刷新处理函数
   */
  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await loadUserProgress();
    setRefreshing(false);
  }, []);

  /**
   * 获取排名颜色
   */
  const getRankColor = (rank) => {
    switch (rank) {
      case 1: return '#FFD700'; // 金色
      case 2: return '#C0C0C0'; // 银色
      case 3: return '#CD7F32'; // 铜色
      default: return '#666';
    }
  };

  /**
   * 获取排名图标
   */
  const getRankIcon = (rank) => {
    switch (rank) {
      case 1: return '🥇';
      case 2: return '🥈';
      case 3: return '🥉';
      default: return `${rank}`;
    }
  };

  // 页面焦点时加载数据
  useFocusEffect(
    useCallback(() => {
      loadUserProgress();
    }, [])
  );

  // 页面初始化时加载数据
  useEffect(() => {
    loadUserProgress();
  }, []);

  // 更新排行榜数据（根据用户当前XP）
  const sortedLeaderboard = React.useMemo(() => {
    const updated = leaderboardData.map(user => 
      user.name === '你' ? { ...user, xp: userProgress.totalXP, streak: userProgress.currentStreak } : user
    );
    return updated.sort((a, b) => b.xp - a.xp);
  }, [userProgress.totalXP, userProgress.currentStreak]);

  // 加载状态显示
  if (isLoading) {
    return (
      <View style={styles.container}>
        <AppHeader 
          title="排行榜"
          userStats={{
            currentStreak: 0,
            totalXP: 0
          }}
        />
        <View style={styles.loadingContainer}>
          <Text style={styles.loadingText}>加载中...</Text>
        </View>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {/* 自定义头部组件 */}
      <AppHeader 
        title="排行榜"
        userStats={{
          currentStreak: userProgress.currentStreak,
          totalXP: userProgress.totalXP
        }}
        backgroundColor="#FF9500"
        leftIcon="trophy"
      />

      {/* 滚动内容区域 */}
      <ScrollView 
        style={styles.scrollView}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            colors={['#FF9500']}
            tintColor="#FF9500"
          />
        }
        showsVerticalScrollIndicator={false}
      >
        {/* 统计信息网格 */}
        <StatisticsGrid 
          userProgress={userProgress}
          style={styles.statsGrid}
        />

        {/* 排行榜标题 */}
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>本周排行榜</Text>
          <Text style={styles.sectionSubtitle}>看看你在同学中的排名</Text>
        </View>

        {/* 排行榜列表 */}
        <View style={styles.leaderboardContainer}>
          {sortedLeaderboard.map((user, index) => {
            const rank = index + 1;
            const isCurrentUser = user.name === '你';
            
            return (
              <View 
                key={user.id} 
                style={[
                  styles.leaderboardItem,
                  isCurrentUser && styles.currentUserItem
                ]}
              >
                {/* 排名 */}
                <View style={styles.rankContainer}>
                  <Text style={[styles.rankText, { color: getRankColor(rank) }]}>
                    {getRankIcon(rank)}
                  </Text>
                </View>

                {/* 头像 */}
                <View style={styles.avatarContainer}>
                  <Text style={styles.avatar}>{user.avatar}</Text>
                </View>

                {/* 用户信息 */}
                <View style={styles.userInfo}>
                  <Text style={[styles.userName, isCurrentUser && styles.currentUserName]}>
                    {user.name}
                  </Text>
                  <Text style={styles.userStats}>
                    {user.xp} XP • 连击 {user.streak} 天
                  </Text>
                </View>

                {/* 成就徽章 */}
                {rank <= 3 && (
                  <View style={styles.badgeContainer}>
                    <Ionicons 
                      name="ribbon" 
                      size={20} 
                      color={getRankColor(rank)} 
                    />
                  </View>
                )}
              </View>
            );
          })}
        </View>

        {/* 成就列表 */}
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>我的成就</Text>
          <Text style={styles.sectionSubtitle}>解锁更多成就徽章</Text>
        </View>

        <AchievementsList 
          achievements={userProgress.achievements}
          userProgress={userProgress}
          style={styles.achievementsList}
        />

        {/* 底部提示信息 */}
        <BottomTip 
          icon="trophy-outline"
          text="坚持学习，冲击排行榜榜首！"
          style={styles.bottomTip}
        />
      </ScrollView>
    </View>
  );
}

/**
 * 样式定义
 */
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f9fa',
  },
  
  scrollView: {
    flex: 1,
  },

  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f8f9fa',
  },

  loadingText: {
    fontSize: 16,
    color: '#666',
    fontFamily: 'System',
  },

  statsGrid: {
    marginHorizontal: 16,
    marginTop: 16,
    marginBottom: 16,
  },

  sectionHeader: {
    marginHorizontal: 16,
    marginVertical: 12,
  },

  sectionTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 4,
    fontFamily: 'System',
  },

  sectionSubtitle: {
    fontSize: 16,
    color: '#666',
    fontFamily: 'System',
  },

  // 排行榜样式
  leaderboardContainer: {
    marginHorizontal: 16,
    backgroundColor: '#fff',
    borderRadius: 12,
    overflow: 'hidden',
    marginBottom: 20,
  },

  leaderboardItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },

  currentUserItem: {
    backgroundColor: '#fff3cd',
    borderLeftWidth: 4,
    borderLeftColor: '#FF9500',
  },

  rankContainer: {
    width: 40,
    alignItems: 'center',
  },

  rankText: {
    fontSize: 18,
    fontWeight: 'bold',
  },

  avatarContainer: {
    marginLeft: 12,
    marginRight: 16,
  },

  avatar: {
    fontSize: 32,
  },

  userInfo: {
    flex: 1,
  },

  userName: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    marginBottom: 4,
  },

  currentUserName: {
    color: '#FF9500',
    fontWeight: 'bold',
  },

  userStats: {
    fontSize: 14,
    color: '#666',
  },

  badgeContainer: {
    marginLeft: 12,
  },

  achievementsList: {
    marginHorizontal: 16,
    marginBottom: 16,
  },

  bottomTip: {
    marginHorizontal: 16,
    marginVertical: 20,
  },
});